// 导入图片
import logo from '@/assets/logo.png'
// 导入 antd 组件库
import { Card, Form, Input, Button, Checkbox } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
// 导入action
import { login } from '@/store/actions/login'
// 导入组件样式
import './Login.scss'

export const Login = () => {
  const dispatch = useDispatch()
  // 创建 history 实例
  const history = useHistory()

  // 获取redux 中的 token
  const token = useSelector(state => state.login)
  console.log('获取到的token', token)

  const onFinish = async values => {
    console.log('Success:', values)
    // 发起action
    await dispatch(login(values.mobile, values.code))
    // 页面跳转
    history.replace('/home')
  }

  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo)
  }
  return (
    <div className="login">
      {/* 登录card容器 */}
      <Card
        className="geek-card"
        bordered={false}
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center'
        }}
      >
        {/* logo */}
        <img className="login-logo" src={logo} alt="" />
        {/* 表单 */}
        <Form
          validateTrigger={['onBlur', 'onChange']} //统一制定表单元素验证触发时机
          initialValues={{
            mobile: '13911111111', //测试时方便
            code: '246810',
            remember: true // 表单初始值设置
          }}
          onFinish={onFinish} // 表单提交验证通过回调
          onFinishFailed={onFinishFailed} // 表单验证失败回调
          autoComplete="off" // 是否打开表单的输入记忆功能
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对'
              },
              {
                required: true,
                message: '请输入手机号'
              }
            ]}
          >
            <Input size="large" placeholder="请输入手机号" maxLength={11} />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              {
                pattern: /^[1-9]\d*$/,
                message: '验证码要求数字'
              },
              {
                len: 6,
                message: '验证码6位'
              },
              {
                required: true,
                message: '请输入验证码'
              }
            ]}
          >
            <Input size="large" placeholder="请输入验证码" maxLength={6} />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked">
            <Checkbox style={{ color: '#1890ff' }}>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button size="large" type="primary" htmlType="submit" style={{ width: '100%' }}>
              登 录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
